# -*- coding: utf-8 -*-
from flask import render_template, request, jsonify, session
from framework.views import view_blue
from framework.model import User
import hashlib
from framework.app import db


@view_blue.route("/login", methods=['GET', 'POST'], endpoint="login")
def login():
    if request.method == "POST":
        try:
            username = request.form.get("username")
            password = request.form.get("password")
            user_result = User.query.filter( User.username == username ).first()
            if not user_result:
                raise ValueError("用户信息不存在!")
            password_md5 = hashlib.md5(password.encode("utf8")).hexdigest()
            if password_md5 != user_result.password_hash:
                raise ValueError("密码错误!")
            session['user_id'] = user_result.id
            session['username'] = user_result.username
            return jsonify({"code":200, "msg": "success"})
        except Exception as e:
            return jsonify({"code": 204, "msg": repr(e)})
    else:
        return render_template('login.html', title='Sign In')


@view_blue.route("/register", methods=['GET', 'POST'], endpoint="register")
def register():
    if request.method == "POST":
        try:
            username = request.form.get("username")
            password = request.form.get("password")
            email = request.form.get("email")
            confirm_password = request.form.get("confirm_password")
            if password != confirm_password:
                raise ValueError("密码不一致！")
            
            user = User()
            user.username = username
            user.email = email
            user.password_hash = hashlib.md5(password.encode("utf8")).hexdigest()
            db.session.add(user)
            db.session.commit()
            return jsonify({"code": 200, "msg": "success"})
        except Exception as e:
            return jsonify({"code": 204, "msg": repr(e)})
    else:
        return render_template('register.html', title='Sign In')
